package es.udc.pfc.davidparedes.web.pages.user;

import java.util.List;

import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;

import es.udc.pfc.davidparedes.model.storeservice.StoreService;
import es.udc.pfc.davidparedes.model.storeservice.UniverseRowStatsDTO;
import es.udc.pfc.davidparedes.model.universe.Universe;
import es.udc.pfc.davidparedes.model.universemanager.UniverseManager;
import es.udc.pfc.davidparedes.model.userprofile.UserProfile;
import es.udc.pfc.davidparedes.model.userservice.UserService;
import es.udc.pfc.davidparedes.model.util.GlobalNames;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.MANAGER_OR_ABOVE)
public class UniverseStats {
	
	@Property
	private UserProfile userProfile;
	
	@Property
	private Universe universe;
	
	@Property
	private List<UniverseRowStatsDTO> stats;
	
	@Property
	private UniverseRowStatsDTO userRow;
	
	@Property
	private Long weekTotal;
	
	@Property
	private Long monthTotal;
	
	@Property
	private Long trimesterTotal;
    
    @SessionState(create=false)
    private UserSession userSession;
    
    @Inject
    private UserService userService;
    
    @Inject
    private StoreService storeService;
    
    @Inject
    private Messages messages;
    
    void onActivate(Long id) throws InstanceNotFoundException {
		userProfile = userService.findUserProfile(userSession.getUserProfileId());
		if (userProfile instanceof UniverseManager) {
			UniverseManager manager = (UniverseManager) userProfile;
			universe = manager.getUniverse();
		} else {
			universe = storeService.findUniverse(id);
		}
		
		stats = storeService.getUniverseStats(universe.getUniverseId());
		weekTotal = (long) 0;
		monthTotal = (long) 0;
		trimesterTotal = (long) 0;
		for (UniverseRowStatsDTO row : stats) {
			weekTotal += row.getWeekMillis();
			monthTotal += row.getMonthMillis();
			trimesterTotal += row.getTrimesterMillis();
		}
		
    }
    
    public boolean isDirector() {
   		if (userSession.getUserType().equals(GlobalNames.USER_TYPE_DIRECTOR)) {
   			return true;
   		}
        return false;
	}
    
    public String formatTime(Long n) {
   		Integer h = (int) (n / (1000*60*60));
   		Integer m = (int) ((n % (1000*60*60)) / (1000*60));
   		String text = h + " " + messages.get("hours");
   		if (m > 0) {
   			text += ", " + m + " " + messages.get("minutes");
   		}
   		return text;
   	}

}
